/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package chmod

import (
	"errors"

	"gitee.com/banggua/ggtsync/cmdutil"
	"gitee.com/banggua/ggtsync/config"
	"gitee.com/banggua/ggtsync/logger"
	"gopkg.in/yaml.v2"
)

const (
	PluginName = "chmod"
)

type chmodPlugin struct {
	path string
}

var (
	DefaultPlugin = &chmodPlugin{}
)

func (cp *chmodPlugin) Test(args map[string]string) error {
	if len(args) != 1 {
		logger.Errorf("%v", errors.New("invalid arguments"))
		return errors.New("invalid arguments")
	}
	// 1 path
	if _, exist := args["path"]; !exist {
		logger.Errorf("%v", errors.New("args.path field does not exist"))
		return errors.New("args.path field does not exist")
	}
	return nil
}

func (cp *chmodPlugin) Templet() string {
	var chmodYaml = &config.Plugin{
		Name:  PluginName,
		Order: 1,
		Args:  map[string]string{"path": "/mirrors"},
	}
	out, _ := yaml.Marshal(&chmodYaml)
	return string(out)
}

func (cp *chmodPlugin) Handle(project *config.Project, args map[string]string) error {
	err := cmdutil.Run("", "chmod", "a+rw", "-R", args["path"])
	if err != nil {
		logger.Errorf("%v", err)
		return err
	}
	return nil
}
